package com.itheima.service.system.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.common.utils.MailUtil;
import com.itheima.common.utils.UtilFuns;
import com.itheima.dao.system.UserDao;
import com.itheima.doamin.system.User;
import com.itheima.service.system.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Override
    public PageInfo findAll(String companyId,int page,int size) {
        //进行分页查询
        PageHelper.startPage(page,size);
        List<User> users = userDao.findAll(companyId);
        return new PageInfo(users);
    }

    @Override
    public List<User> findAll(String companyId){
        return userDao.findAll(companyId);
    }

    @Override
    public User findById(String userId) {
        return userDao.findById(userId);
    }

    @Override
    public void delete(String userId) {
        userDao.delete(userId);
    }

    @Override
    public void save(User user) throws Exception {
        user.setId(UtilFuns.getUUID());
        userDao.save(user);
        String subject="注册成功";
        String content=user.getUserName()+"，用户你好,你的SaaS系统账号以成功开通，请使用账号:"
                +user.getUserName()+",密码:"+user.getPassword()+"进行登录";
        MailUtil.sendMsg(user.getEmail(),subject,content);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public List<String> userRoleStr(String id) {
        return userDao.userRoleStr(id);
    }

    @Override
    public void changeRole(String userid, String[] roleIds) {
        //删除用户原有角色
        userDao.deleteRoleByUserId(userid);
        for (String roleId:roleIds){
            userDao.saveRoleAndUser(userid,roleId);
        }
    }

    @Override
    public User toLogin(String email) {
        return userDao.toLogin(email);
    }
}
